package org.example.controller;

import org.example.domain.Post;
import org.example.domain.Comment;
import org.example.myEnum.ErrorCode;
import org.example.response.ApiResponse;
import org.example.service.PostService;
import org.example.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/community")
public class PostController {

    @Autowired
    private PostService postService;
    
    @Autowired
    private CommentService commentService;

    // 获取所有帖子
    @GetMapping("/posts/getALL")
    public ApiResponse<List<Post>> getAllPosts(@RequestParam(required = false) String userId) {
        try {
            List<Post> posts = postService.getAllPosts(userId);
            
            // 获取所有帖子的评论（包括回复）
            for (Post post : posts) {
                // 获取帖子的所有评论（父级评论）
                List<Comment> parentComments = commentService.getPostComments(post.getId());
                
                // 为每个父级评论获取其回复
                for (Comment parentComment : parentComments) {
                    // 获取该评论的所有父子复
                    List<Comment> replies = commentService.getCommentReplies(parentComment.getId());
                    parentComment.setReplies(replies);
                    // 设置回复数量
                    parentComment.setReplyCount(replies.size());
                }
                
                // 设置帖子的评论列表
                post.setComments(parentComments);
                // 设置帖子的总评论数（包括回复）
                int totalComments = postService.getTotalCountByPostId(post.getId());
                post.setCommentCount(totalComments);
            }
            
            return ApiResponse.success(posts);
        } catch (Exception e) {
            e.printStackTrace(); // 添加日志记录
            return ApiResponse.error(ErrorCode.FAIL_GET_POST.getCode(), "获取帖子失败: " + e.getMessage());
        }
    }

    // 创建新帖子
    @PostMapping("/posts/create")
    public ApiResponse<Post> createPost(@RequestBody Post post) {
        try {
            return ApiResponse.success(postService.createPost(post));
        } catch (Exception e) {
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "发布帖子失败: " + e.getMessage());
        }
    }

    // 点赞帖子
    @PostMapping("/posts/{postId}/like")
    public ApiResponse<Post> likePost(@PathVariable String postId, @RequestParam String userId) {
        try {
            return ApiResponse.success(postService.likePost(postId, userId));
        } catch (Exception e) {
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "点赞失败: " + e.getMessage());
        }
    }
}
